package com.aforce3.trailertracer.utils;

import javax.media.j3d.Transform3D;
import javax.vecmath.AxisAngle4d;
import javax.vecmath.Vector3d;

public class VectorModifier
{
	public static Vector3d calculateVectorRefraction(Vector3d incomingVector, Vector3d normal, double n1, double n2){
		Vector3d temp = new Vector3d();
		
		//flips incoming vector to have the same orientation as normal
		//Vector3d outDirection = new Vector3d(incomingVector);
		//outDirection.scale(-1);
		
		//sin(t1)/sin(t2) = n2 / n1
		//t2 = sin-1(n1 * sin(t1) / n2)
		
		temp.add(normal);
		float dotVal = (float) temp.dot(incomingVector);
		//absolute value of dot
		float positiveDot = Math.abs(dotVal);
		
		double t1 = Math.acos(positiveDot);
		
		double t2 = Math.asin(n1 * Math.sin(t1) / n2);
		
		Vector3d axis = new Vector3d();
		
		if (dotVal > 0){
			axis.cross(normal, incomingVector);
		}else{
			axis.cross(incomingVector, normal);
		}
		
		AxisAngle4d a = new AxisAngle4d(axis, t2);
		
		Transform3D rotation = new Transform3D();
		rotation.set(a);
		
		Vector3d retval = new Vector3d(normal);
		retval.scale(-1);
		//rotate the inner vector by this new angle
		rotation.transform(retval);
		
		return retval;
	}
}
